package antLogic;

import java.util.Vector;

/**
 * Created by IntelliJ IDEA.
 * User: Mark the intern
 * Date: 10-Jul-2007
 * Time: 3:53:37 PM
 */
public class Ant extends PhysicalObject {

    Vector<Event> memory;
    ThoughtProcess brain;
    Integer energy;
    Counter bearing;
    Integer stepCount;
    Locomotion legs;

    Integer sleepTime;

    Boolean needsToThink;
    Vector<Integer> criticalEvents;

    public Ant(int id, Counter bearing, int velocity, int sleepTime) {
        super(id, velocity);
        memory = new Vector<Event>();
        brain = new ThoughtProcess(this);
        energy = 100;
        this.bearing = bearing;
        stepCount = 0;
        legs = new Locomotion(this);

        this.sleepTime = sleepTime;

        needsToThink = true;
        criticalEvents = new Vector<Integer>();

        memory.add(new Event(Event.BORN, stepCount, null));
        criticalEvents.add(Event.BORN);
        AntManager.antMgr.numAntsReady++;
    }

    public ThoughtProcess getBrain() {
        return brain;
    }

    public Integer getStepCount() {
        return stepCount;
    }

    public Locomotion getLegs() {
        return legs;
    }

    public Boolean getNeedsToThink() {
        return needsToThink;
    }

    public Vector<Integer> getCriticalEvents() {
        return criticalEvents;
    }

    public synchronized void queueEvent(Event newEvent) {
        memory.add(newEvent);
        stepCount = newEvent.getStep();
        for (Integer criticalEvent : criticalEvents) {
            if (newEvent.getEventType().equals(criticalEvent)) {
                needsToThink = true;
                setPriority(Thread.NORM_PRIORITY + 2);
                break;
            }
        }
    }

    public Vector<Event> getMemory() {
        return memory;
    }

    public Integer getEnergy() {
        return energy;
    }

    public Counter getBearing() {
        return bearing;
    }

    public Integer getAntId() {
        return objectId;
    }

    public void setBearing(Integer bearing) {
        this.bearing.setValue(bearing);
    }

    public void run() {
        while (energy > 0) {
            try {
                if (needsToThink) {
                    brain.think();
                }
                Thread.sleep(sleepTime);
                yield();
            } catch (InterruptedException e) {
                AntManager.antMgr.rmAnt(objectId);
                energy = -1;
            }
        }
        AntManager.antMgr.logWarn(this, "Ant #" + objectId + " has died.");
    }
}
